package com.wzm.service;

import org.json.JSONException;
import org.json.JSONObject;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import com.wzm.manager.AppConfig;
import com.wzm.manager.AppManager;
import com.wzm.moviepic.AppApplication;
import com.wzm.utils.Logger;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.IBinder;
import android.view.WindowManager;
import android.widget.Toast;

public class UpdateService extends Service {
	
	private int versionCode = 0;
	private String versionName = null;
	private Context mContext = null;
	private FinalHttp fh = null;
	
	private String updatemsg = null;
	private String updateApk = null;
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		mContext = this;
		
		getCurrentVersion();
		fh = AppManager.getInstance(mContext).getFh();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	@Deprecated
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
		
		//参数：
    	
		if(AppApplication.getInstance().mNetWorkState==0)
		{
			Logger.info("没有网络，勿需更新");
			stopSelf();
		}else{
			AjaxParams params = new AjaxParams();
			params.put("movieid","0");
			params.put("limit", "1000");
			fh.post(AppConfig.CHECKVERSION, params,new AjaxCallBack<Object>() {

				@Override
				public void onSuccess(Object t) {
					// TODO Auto-generated method stub
					//super.onSuccess(t);
					String json = t.toString();
					try {
						JSONObject result = new JSONObject(json);
						String status = result.getString("status");
						if(status.equals("1"))
						{
							Logger.info("有更新");
							//int vc = Integer.valueOf(result.getString("vc"));
							updatemsg = result.getString("msg");
							updateApk = result.getString("apkurl");
							//showUpdataDialog();
						}else{
							Logger.info("没有更新");
							stopSelf();
						}
						
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						//e.printStackTrace();
						Logger.error(e.getMessage());
						stopSelf();
					}
				}

				@Override
				public void onFailure(Throwable t, String strMsg) {
					// TODO Auto-generated method stub
					//super.onFailure(t, strMsg);
					stopSelf();
				}
				
			});
		}
		
	}
	
	
	 public void getCurrentVersion() {   
        try {   
            PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);   
            this.versionCode = info.versionCode;   
            this.versionName = info.versionName;   
        } catch (NameNotFoundException e) {   
            Logger.error("error:"+e.getMessage());   
        }   
    }   
	 
	 
	    /*  
	     *   
	     * 弹出对话框通知用户更新程序   
	     *   
	     * 弹出对话框的步骤：  
	     *  1.创建alertDialog的builder.    
	     *  2.要给builder设置属性, 对话框的内容,样式,按钮  
	     *  3.通过builder 创建一个对话框  
	     *  4.对话框show()出来    
	     */    
	    protected void showUpdataDialog() {    
	        AlertDialog.Builder builer = new Builder(mContext) ;     
	        builer.setTitle("有新版本更新");    
	        builer.setMessage(updatemsg);    
	        //当点确定按钮时从服务器上下载 新的apk 然后安装      
	        builer.setPositiveButton("下载更新", new OnClickListener() {    
	        public void onClick(DialogInterface dialog, int which) {    
	                //Log.i(TAG,"下载apk,更新");    
	                //downLoadApk();    
	        		stopSelf();
	            }       
	        });    
	        //当点取消按钮时进行登录     
	        builer.setNegativeButton("取消", new OnClickListener() {    
	            public void onClick(DialogInterface dialog, int which) {    
	                // TODO Auto-generated method stub     
	                //LoginMain();  
	            	stopSelf();
	            }    
	        });    
	        AlertDialog dialog = builer.create();  
	        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
	        dialog.show();    
	    }   

}
